package org.summerframework.component.security.spring;

import com.fasterxml.jackson.annotation.JsonIgnore;
import org.summerframework.component.security.LoginData;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.Collection;
import java.util.List;

/**
 * @author 石超
 * @version v1.0.0
 */
public class LoginSecurityData implements Authentication {
    private static final long serialVersionUID = -6685218371499873910L;
    private LoginData loginData;
    private List<GrantedAuthority> grantedAuthorities;
    private static final GrantedAuthority ANY_GRANTED_AUTHORITY = new SimpleGrantedAuthority("ANY");

    public LoginSecurityData(LoginData loginData, List<GrantedAuthority> grantedAuthorities) {
        this.loginData = loginData;
        this.grantedAuthorities = grantedAuthorities;
        this.grantedAuthorities.add(ANY_GRANTED_AUTHORITY);
    }

    @Override
    @JsonIgnore
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.grantedAuthorities;
    }

    @Override
    @JsonIgnore
    public Object getCredentials() {
        return this.loginData.getUserId();
    }

    @Override
    @JsonIgnore
    public Object getDetails() {
        return this.loginData.getUserName();
    }

    @Override
    @JsonIgnore
    public Object getPrincipal() {
        return this.loginData;
    }

    @Override
    @JsonIgnore
    public boolean isAuthenticated() {
        return this.loginData.isLogin();
    }

    @Override
    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        if (!isAuthenticated) {
            this.loginData.setUser(null);
        }
    }

    @Override
    public String getName() {
        return this.loginData.getName();
    }

    public Long getUserId() {
        return this.loginData.getUserId();
    }

    void setGrantedAuthorities(List<GrantedAuthority> grantedAuthorities) {
        this.grantedAuthorities = grantedAuthorities;
    }

    public LoginData getLoginData() {
        return loginData;
    }
}
